﻿#include "editimagewidget.h"
#include <QApplication>
#include <QVBoxLayout>
#include <QDesktopWidget>
#include <QWindow>
#include <QScreen>
#include <QTime>
#include <QDebug>
#include <QFileDialog>
#include <QClipboard>
#include <QPushButton>

#include "imageediter.h"
#include "pensetting.h"
#include "controlwidget.h"

const int MARGIN = 1;

extern QString getSavePath();

EditImageWidget::EditImageWidget(QImage origImg,QWidget *parent)
    : QDialog(parent),m_origImg(origImg)
{
#ifdef Q_OS_WIN32
//    ratio = scrPix->devicePixelratio(); //2;
    double dpi = QApplication::primaryScreen()->logicalDotsPerInch();

    ratio = 1;
    if (dpi <= 108) { // 0-96-108
        ratio = 1;
    } else if (dpi <= 132) { // 108-120-132
        ratio = 1.25;
    } else if (dpi <= 168) { // 132-144-168
        ratio = 1.5;
    } else { // 168-192-inf
        ratio = 2;
    }
    qDebug() << "ratio: " << ratio << " dpi: " << dpi;
#else
    ratio = 1;
#endif

    this->setWindowTitle(QStringLiteral("图片编辑"));
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_DeleteOnClose,true); //窗口关闭时释放内存
    //setAttribute(Qt::WA_TranslucentBackground, true);

    this->setStyleSheet("QDialog{ background-color: rgb(230, 230, 230); border: 1px solid rgb(200, 200, 200);}");

    setContextMenuPolicy(Qt::NoContextMenu);

//    int ratio = QApplication::desktop()->devicePixelratio();

    m_imageEditer = new ImageEditer(this);
    m_imageEditer->setCurrentSize(3 * ratio);
    m_imageEditer->setCurrentColor(Qt::red);

    Qt::WindowFlags nType = Qt::FramelessWindowHint | Qt::Tool;

    m_pensetting = new PenSetting(this);
    m_pensetting->setWindowFlags(nType);
    connect(m_imageEditer,&ImageEditer::cliped,this,&EditImageWidget::on_cliped);
    connect(m_imageEditer,&ImageEditer::undoEnableChanged,this,[=](bool undoEnable){
        if(m_control){
            m_control->setReturnEnabled(undoEnable);
        }
    });

    connect(m_pensetting,&PenSetting::sizeChanged,this,[=](PenSize size){
        int ps = 3 * ratio;
        if (size == PS_SMALL) {
            ps =  1 * ratio;
        }else if(size == PS_NORMAL) {
            ps =  3 * ratio;
        }else if (size == PS_LARGE){
            ps =  5 * ratio;
        }

        m_imageEditer->setCurrentSize(ps);
    });

    connect(m_pensetting,&PenSetting::colorChanged,this,[=](QColor color){
        m_imageEditer->setCurrentColor(color);
    });

    m_control =  new ControlWidget(this);
    m_control->setWindowFlags(nType);
    initConnectors();

    QVBoxLayout *layout = new QVBoxLayout(this);    //在control上建立水平布局
    layout->setMargin(MARGIN);

    QFrame *frame = new QFrame(this);
    frame->setFixedHeight(24 * ratio);
    frame->installEventFilter(this);
    frame->setMouseTracking(true);

    QHBoxLayout *frameLayout = new QHBoxLayout(this);
    frameLayout->addStretch(1);
    QPushButton* btn = new QPushButton(frame);
    btn->setFixedSize(15 * ratio, 15 * ratio);
    btn->setFlat(true);
    btn->setIcon(QIcon(":/image/ScreenCapture_toolbar_cross_normal.tiff"));
    frameLayout->addWidget(btn);
    frame->setLayout(frameLayout);

    connect(btn,&QPushButton::clicked,this,[=](bool b){
       this->close();
    });

    layout->addWidget(frame);
    layout->addWidget(m_imageEditer);         //将控制窗口应用于水平布局
    setLayout(layout);

    QRect screenRect = QApplication::desktop()->geometry();
    QRect imgRect = m_origImg.rect();

    int imgWidth = imgRect.width();
    int imgheight = imgRect.height();
    if(imgWidth > screenRect.width() - 200){
        imgWidth = screenRect.width() - 200;
    }

    if(imgheight > screenRect.height() - 300){
        imgheight = screenRect.height() - 300;
    }

    QImage img = m_origImg;
    if(imgWidth != imgRect.width() || imgheight != imgRect.height()){
        img = m_origImg.scaled(imgWidth,imgheight,Qt::KeepAspectRatio,Qt::SmoothTransformation);
    }

    m_imageEditer->setimagetolabel(img);
    setFixedSize(img.width()+ MARGIN,img.height()+MARGIN + frame->height());

    m_control->show();
}

EditImageWidget::~EditImageWidget()
{
    //delete m_control;
    //delete m_pensetting;
}

void EditImageWidget::moveToScreenCenter() {
    QRect rect =  QApplication::primaryScreen()->geometry();
    int x = (rect.width() - this->width()) / 2 + rect.x();
    int y = (rect.height() - this->height()) / 2 + rect.y();

    this->move(x,y);
}

void EditImageWidget::initConnectors()
{
    connect(m_control,&ControlWidget::drawRect,this,[=](){
        m_imageEditer->setrectangleenable();
        m_pensetting->setSettingType(ST_NORMAL);
        m_pensetting->show();
    });

    connect(m_control,&ControlWidget::drawLine,this,[=](){
        m_imageEditer->setdrawlineenable();
        m_pensetting->setSettingType(ST_NORMAL);
        m_pensetting->show();
    });

    connect(m_control,&ControlWidget::drawText,this,[=](){
        m_imageEditer->settexteditenable();
        m_pensetting->setSettingType(ST_TEXT);
        m_pensetting->show();
    });


    connect(m_control,&ControlWidget::drawArrow,this,[=](){
        m_imageEditer->setdrawarrowenable();
        m_pensetting->setSettingType(ST_NORMAL);
        m_pensetting->show();
    });

    connect(m_control,&ControlWidget::drawArrow2,this,[=](){
        m_imageEditer->setdrawarrow2enable();
        m_pensetting->setSettingType(ST_NORMAL);
        m_pensetting->show();
    });


    connect(m_control,&ControlWidget::drawRound,this,[=](){
        m_imageEditer->setroundenable();
        m_pensetting->setSettingType(ST_NORMAL);
        m_pensetting->show();
    });

    connect(m_control,&ControlWidget::drawMosaic,this,[=](){
        m_imageEditer->setdrawmosaicnable();
        m_pensetting->setSettingType(ST_MOSAIC);
        m_pensetting->show();
    });

    connect(m_control,&ControlWidget::drawFace,this,[=](){
        m_imageEditer->setdrawfacenable();
        m_pensetting->hide();
    });

    connect(m_control,&ControlWidget::clip,this,[=](){
        m_imageEditer->setclipable();
        m_pensetting->hide();
    });


    connect(m_control,&ControlWidget::undo,this,[=](){
       m_imageEditer->undo();
    });

    connect(m_control,&ControlWidget::forward,this,[=](){
       doForward();
       close();
       Exit(3);
    });

    connect(m_control,&ControlWidget::save,this,[=](){
        savePixmap();
        close();
        Exit(2);
    });

    connect(m_control,&ControlWidget::cancel,this,[=](){
        close();
        Exit(1);
    });

    connect(m_control,&ControlWidget::finish,this,[=](){
        complete();
    });
}

void EditImageWidget::cancel()
{
    close();
    Exit(1);
}

void EditImageWidget::doForward()
{
    QPixmap img = m_imageEditer->resultimage();
    emit forward(img);
}

void EditImageWidget::on_cliped(QRect rect)
{
    QPoint p = this->mapFromGlobal(rect.topLeft());

    QPixmap pixmap = m_imageEditer->resultimage();

    this->setFixedSize(rect.width(),rect.height());

    QImage selectimage=pixmap.copy(QRect(p.x(),p.y(),rect.width(),rect.height())).toImage();
    m_imageEditer->setimagetolabel(selectimage);

    moveControls();
}

void EditImageWidget::moveControls()
{
    QScreen *scrPix = windowHandle()->screen();

    m_control->setDpi(ratio);
    m_pensetting->setDpi(ratio);

    QPoint tfPoint = this->mapToGlobal(QPoint(0,0));

    int bottomRightX = tfPoint.x() + this->width();
    int bottomRightY = tfPoint.y() + this->height();

    int controlW = CONTROL_WIDTH * ratio;
    int controlH = CONTROL_HEIGHT * ratio;
    int controlX = bottomRightX - controlW;

    m_control->setGeometry(controlX, bottomRightY+ CONTROL_HEIGHTMARGIN, controlW, controlH);
    m_pensetting->setGeometry(controlX + 10,bottomRightY+10+controlH,280 * ratio,30 *ratio);
}

void EditImageWidget::resizeEvent(QResizeEvent *event)
{
    moveControls();
}

void EditImageWidget::closeEvent(QCloseEvent *event)
{
    this->Exit(1);
    QWidget::closeEvent(event);
}

void EditImageWidget::moveEvent(QMoveEvent *event)
{
    QWidget::moveEvent(event);
    this->moveControls();
}

void EditImageWidget::hideEvent(QHideEvent *event)
{
     QWidget::hideEvent(event);
     m_control->hide();
     m_pensetting->hide();
}

void EditImageWidget::showEvent(QShowEvent *event)
{
     QWidget::showEvent(event);
     m_control->show();
}

bool EditImageWidget::eventFilter(QObject *obj, QEvent *e)
{
    if(e->type() == QEvent::MouseButtonPress){
        QMouseEvent *event = (QMouseEvent *)e;
        if(event->buttons() & Qt::LeftButton){
            m_isPress = true;
            m_startPoint = event->globalPos() - this->pos();
        }
        return true;
    }
    else if(e->type() == QEvent::MouseButtonRelease) {
        m_isPress = false;
        return true;
    }
    else if(e->type() == QEvent::MouseMove)
    {
        QMouseEvent *event = (QMouseEvent *)e;
        if (m_isPress)
        {
            this->move(event->globalPos()-m_startPoint);
            return true;
        }
    }

    return QObject::eventFilter(obj,e);
}

void EditImageWidget::Exit(int code)
{
    emit finished(code);
}

//保存截取出来的图片
void EditImageWidget::savePixmap()
{
    QString filename = getSavePath();
    if(filename.length()>0){
        QFileInfo fileInfo(filename);
        QImage pimage= m_imageEditer->HDResultImage(m_origImg);
        pimage.save(filename, "jpg");
    }
}

void EditImageWidget::complete()
{
    QClipboard *board = QApplication::clipboard();
    QImage pimage= m_imageEditer->HDResultImage(m_origImg);
    //board->setImage(pimage);
    emit forward(QPixmap::fromImage(pimage));

    close();
    Exit(0);
}
